package com.spring.demo8.eg12;

import org.junit.Test;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;

/**
 * @author vhans
 */
public class DestructionAwareBeanPostProcessorTest {
    @Test
    public void test() {
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        // 添加自定义的DestructionAwareBeanPostProcessor
        factory.addBeanPostProcessor(new MyDestructionAwareBeanPostProcessor());

        // 注册3个单例bean
        factory.registerBeanDefinition("serviceA1", BeanDefinitionBuilder
                .genericBeanDefinition(ServiceA.class)
                .getBeanDefinition());
        factory.registerBeanDefinition("serviceA2", BeanDefinitionBuilder
                .genericBeanDefinition(ServiceA.class)
                .getBeanDefinition());
        factory.registerBeanDefinition("serviceA3", BeanDefinitionBuilder
                .genericBeanDefinition(ServiceA.class)
                .getBeanDefinition());

        // 触发所有单例bean初始化
        factory.preInstantiateSingletons();

        System.out.println("销毁serviceA1");
        factory.destroySingleton("serviceA1");

        System.out.println("触发所有单例bean的销毁");
        factory.destroySingletons();
    }

    @Test
    public void test1() {
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();

        factory.addBeanPostProcessor(new MyDestructionAwareBeanPostProcessor());
        // 添加CommonAnnotationBeanPostProcessor
        factory.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor());

        factory.registerBeanDefinition("serviceB", BeanDefinitionBuilder
                .genericBeanDefinition(ServiceB.class)
                .getBeanDefinition());

        factory.preInstantiateSingletons();

        System.out.println("销毁serviceB");

        factory.destroySingleton("serviceB");
    }
}
